﻿/* Sharepoint Developer's Hub 
 * Author       : Ram Prasad Meenavalli (ram@spdeveloper.co.in)
 * Date         : Jun 30 2012
 * Description  : This class represents a custom CMDLET (Upgrade-SPSolution) which updates the solution and installs
 * the newly added features to the Farm.
 */
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;
using SPDev.Administration;

namespace SPDev.Powershell
{
    [Cmdlet("Upgrade", "SPSolution", SupportsShouldProcess = true), SPCmdlet(RequireLocalFarmExist = true)]
    internal sealed class SPCmdletUpgradeSolution : SPCmdlet
    {
        #region Properties
        private string m_Time;
        private SPSolutionPipeBind m_Identity;
        private string m_LiteralPath;
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
        public SPSolutionPipeBind Identity
        {
            get
            {
                return this.m_Identity;
            }
            set
            {
                this.m_Identity = value;
            }
        }
        [Parameter(Mandatory = true)]
        public string LiteralPath
        {
            get
            {
                return this.m_LiteralPath;
            }
            set
            {
                this.m_LiteralPath = value;
            }
        }
        [Parameter(Mandatory = false)]
        public string Time
        {
            get
            {
                return this.m_Time;
            }
            set
            {
                this.m_Time = value;
            }
        }
        [Parameter(Mandatory = false)]
        public SwitchParameter CASPolicies
        {
            get;
            set;
        }
        [Parameter(Mandatory = false)]
        public SwitchParameter GACDeployment
        {
            get;
            set;
        }
        [Parameter(Mandatory = false)]
        public SwitchParameter Local
        {
            get;
            set;
        }
        [Parameter(Mandatory = false)]
        public SwitchParameter Force
        {
            get;
            set;
        }
        private SPSolution spSolution;
        private DateTime dateTime;
        #endregion

        protected override void InternalBeginProcessing()
        {
            base.InternalBeginProcessing();
            if (this.Local && !string.IsNullOrEmpty(this.Time))
            {
                throw new SPCmdletException("Both Local and Time cannot be specified. Please specify only one of these");
            }
            if (!string.IsNullOrEmpty(this.Time))
            {
                this.dateTime = DateTime.Parse(this.Time, CultureInfo.CurrentCulture);
                if (this.dateTime.CompareTo(DateTime.Now) < 0)
                {
                    throw new SPCmdletException("Invalid Time");
                }
            }
            else
            {
                this.dateTime = DateTime.Now;
            }
            if (!File.Exists(this.LiteralPath))
            {
                base.WriteError(new FileNotFoundException("There no Solution package found at the specified location"), ErrorCategory.ReadError, null);
                base.SkipProcessCurrentRecord();
            }
        }

        protected override void InternalValidate()
        {
            this.spSolution = this.Identity.Read();

            bool containsGlobalAssembly = spSolution.ContainsGlobalAssembly;
            bool containsCasPolicy = spSolution.ContainsCasPolicy;

            if (containsCasPolicy && !this.CASPolicies)
            {
                base.WriteError(new SPCmdletException(@"Upgrade-SPSolution : The solution has Code Access Security Policies (CAS). Use the -CASPolicies parameter to deploy."), ErrorCategory.InvalidOperation, this);
                base.SkipProcessCurrentRecord();
            }

            if (containsGlobalAssembly && !this.GACDeployment)
            {
                base.WriteError(new SPCmdletException(@"Upgrade-SPSolution : The solution needs to install assemblies in the Global Assembly Cache (GAC). If you fully trust this solution, use the -GACDeployment parameter to deploy."), ErrorCategory.InvalidOperation, this);
                base.SkipProcessCurrentRecord();
            }
        }

        protected override void InternalProcessRecord()
        {
            List<String> beforeFeatures = SPDUtility.GetFeatures(spSolution);
            List<String> afterFeatures = SPDUtility.GetFeatures(LiteralPath);
            IEnumerable<String> newFeatures = afterFeatures.Except(beforeFeatures);
            //Update the Solution
            spSolution.Upgrade(LiteralPath, dateTime);
            //Check if there any new fetures added in the package, and then deploy a one time timer job to install these feautres
            int iCount = afterFeatures.Count - beforeFeatures.Count;
            base.WriteResult(String.Format("{0} new feature/s found", iCount));
            if (0 < iCount)
            {
                SPFeatureInstallationJobDefinition featureInstallationJob = new SPFeatureInstallationJobDefinition(spSolution.Name, spSolution.SolutionId, CultureInfo.CurrentCulture.LCID, SPFarm.Local.TimerService, SPDUtility.MergerFeatureNames(newFeatures), Force.IsPresent);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(dateTime.AddMinutes(1));
                featureInstallationJob.Schedule = schedule;
                try
                {
                    featureInstallationJob.Update();
                }
                catch (Exception ex)
                {
                    if (ex is SPDuplicateObjectException || ex is SPUpdatedConcurrencyException)
                    {
                        throw new InvalidOperationException(SPResource.GetString("SolutionDeploymentAlreadyInProgress", new object[]
                        {
                            this.spSolution.DisplayName
                        }));
                    }
                    throw;
                }

                foreach (var f in newFeatures)
                {
                    base.WriteResult(f);
                }
                base.WriteResult("There will be some delay for these Features to be installed in the farm. Please check after few minutes...");
            }
            if (!SPDUtility.IsAdministrationServiceRunning())
            {
                throw new SPCmdletException("Upgrade-SPSolution : Admin SVC must be running in order to create deployment timer job.");
            }
        }
    }
}
